This guide assumes you already have a Phoenix application set up. If you don’t, check out the Phoenix installation guide first. LiveView is included by default in Phoenix 1.6+.
Build a thermostat
We’ll create a simple thermostat that displays the current temperature and allows users to increase or decrease it.Create the LiveView module
Create a new file at This LiveView defines three essential callbacks:
lib/my_app_web/live/thermostat_live.ex (replace my_app_web with your app’s name):render/1receives the socket assigns and returns the HTML to display using the~Hsigil (HEEx template)mount/3initializes the LiveView state when it first loadshandle_event/3handles the button click event
Add the route
Open your router file at The
lib/my_app_web/router.ex and add a live route:live macro creates a route that serves your LiveView directly.Start the server and test
Start your Phoenix server:Visit
http://localhost:4000/thermostat in your browser. You should see the thermostat with the current temperature and a + button. Click the button and watch the temperature increase in real-time!How it works
The LiveView lifecycle
-
Initial HTTP request: When you first visit
/thermostat, Phoenix renders the LiveView as static HTML through a regular HTTP request. This ensures fast “First Meaningful Paint” and helps with SEO. - WebSocket connection: After the page loads, the JavaScript client (automatically included in Phoenix apps) establishes a WebSocket connection to the server.
-
LiveView process: A new LiveView process is spawned on the server. The
mount/3callback runs again to initialize the state. -
User interaction: When you click a button, the client sends an event to the server over WebSocket. The
handle_event/3callback processes it and updates the state. - Minimal updates: LiveView calculates exactly what changed and sends only the diff to the client. The client efficiently patches the DOM.
Understanding the code
The~H sigil: This is HEEx (HTML+EEx), LiveView’s templating language. It provides:
- HTML validation at compile time
- Automatic XSS protection
- Support for function components
- Interpolation with
{@variable}syntax
phx-click binding: This tells LiveView to send an event to the server when the element is clicked. LiveView supports many bindings: phx-submit, phx-change, phx-focus, phx-blur, and more.
The socket: The socket holds all the state for your LiveView in its assigns. Functions like assign/3 and update/3 return a new socket with updated assigns. Because Elixir data is immutable, LiveView can efficiently track what changed.
Add temperature limits
Let’s make our thermostat more realistic by adding temperature limits and visual feedback:Next steps
Assigns and HEEx
Learn more about templates and data binding
Bindings
Explore all available LiveView bindings
Forms
Build forms with live validation
Components
Create reusable function components